//
//  UIImage+Helper.m
//  DrawImage
//
//  Created by zero on 2017/6/1.
//  Copyright © 2017年 zero. All rights reserved.
//

#import "UIImage+Helper.h"
@implementation UIImage (Helper)

+ (UIImage*)drawImage:(UIImage*)image Scale:(CGFloat)scaleSize{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize), NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage*)drawScreenshot:(UIView*)view{
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
//    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage* screenshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenshot;
}

+ (UIImage*)drawWithImage:(UIImage*)contentImage Title:(NSString*)contentTitle{
    UIColor* bgColor = [UIColor colorWithRed:35/255. green:38/255. blue:43/255. alpha:1];
    //计算长宽
    CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat height = CGRectGetHeight([UIScreen mainScreen].bounds);
    CGFloat borderWidth = 50;
    UIFont *titleFont = [UIFont systemFontOfSize:12];
    CGFloat imageWidth = width - borderWidth * 2;
    CGFloat imageHeight = contentImage.size.height / contentImage.size.width * imageWidth;
    CGFloat titleHeight = [contentTitle boundingRectWithSize:CGSizeMake(imageWidth, 10000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName:titleFont} context:nil].size.height;
    CGFloat titleWidth = imageWidth;
    CGRect imageRect = CGRectMake(borderWidth, borderWidth*2, imageWidth, imageHeight);
    height = CGRectGetMaxY(imageRect)+titleHeight+borderWidth*2;
    
    //必须设置scale，否则文字会模糊
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, [UIScreen mainScreen].scale);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    //填充背景色
    CGContextSetFillColorWithColor(context, bgColor.CGColor);
    CGContextFillRect(context, CGRectMake(0, 0, width, height));
    //绘制图片
    [contentImage drawInRect:imageRect blendMode:kCGBlendModeNormal alpha:1];
    //绘制文字
    [contentTitle drawInRect:CGRectMake(borderWidth, CGRectGetMaxY(imageRect)+borderWidth, titleWidth, titleHeight) withAttributes:@{NSFontAttributeName:titleFont,NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

@end
